public class RecordOutofPlanJointCall{
/**********************************************************************

************************************************************************/
  
    public string CityValue{get;set;}
    public List<SelectOption> MSRList{get;set;}
    public list<place__c> PlaceL{get;set;}
    public user CurrentUser{get;set;}
    public list<User> AllUserList{get;set;}
    public List<user> AllMsr{get;set;}
    public string MSRL{get;set;}
    public string NullCallDateError{get;set;}
    public boolean showError{get;set;}
    public string msg{get;set;}
    public string MonthlyJointCallId{get;set;}
    public date PlanMonth{get;set;}
    public  Map<id,CallPlan__c> AddedCallPlan = new Map<id,CallPlan__c>();
    public List<jointcall__c> UpsertJointCallList
    {
        get
        {
            if(UpsertJointCallList== null){
                UpsertJointCallList= new List<jointcall__c>();             
            }
            return UpsertJointCallList;    
        }
        set;
    }
    //get url id
    public String UrlId
    {
        get{        
                return System.currentPageReference().getParameters().get('retURL').substring(1,16);
           }  
        set;
    }     
    
    public List<jointcall__c> JointCallList
    {
        get{
            if(JointCallList== null){
                JointCallList= new List<jointcall__c>();             
            }
            return JointCallList;
        }
        set;    
    }
    
    public jointcall__c jointCall{
        get{
            if(jointCall== null){
                jointCall= new JointCall__c();             
            }
            return jointcall;
        }
        set;
    }
    
    public list<CallPlanEntry> CallPlan{
        get{
            if(callplan==null)
            callplan=new list<CallPlanEntry>();
            return callplan;
        }
        set;
    }
    public void UpdateRecord()
    {
        list<Monthly_Joint_Call__c> MJCL=[select id,year__c,month__c from Monthly_Joint_Call__c where yearFormula__c=:JointCall.SearchDate__c.year() and monthFormula__c =: JointCall.SearchDate__c.month() and ownerid = :userinfo.getuserid()];

        for(CallPlanEntry cp:CallPlan){
            if(cp.checked){
            
                User Msr = [Select u.Alias From User u where u.id =: cp.callplan.ownerid__c];
                JointCall__c newJointCall=new JointCall__c(
                    CallPlan__c=cp.callplan.id,
                    name=cp.callplan.name,
                    CallPlanOwner18Digit__c=cp.callplan.Monthly_Call_Plan__r.OwnerId,
                    HCPID18digit__c=cp.callplan.HCP__r.Id,
                    MonthlyJointCall__c=MJCL[0].id,
                    isinplan__c=true,
                    MSR_Text__c = Msr.Alias,
                    Owner__c=userinfo.getuserid(),
                    UniqueId__c=string.valueof(cp.callplan.id).substring(0,15)+userinfo.getuserid().substring(0,15)
                );
                if(!AddedCallPlan.containsKey(cp.callplan.id))
                    UpsertJointCallList.add(newJointCall);
               } 
           }
                    
    }    
    public RecordOutofPlanJointCall() {

        placeL=[select Id,Name,Region__r.Name,Subregion__r.Name,Area__r.Name,PlaceType__c  from Place__c];
        CurrentUser=[select Id,Name,UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c from User where Id=:UserInfo.getUserId()];
        Profile prof=[select Name from Profile where Id=: UserInfo.getProfileId()];
        try{
            MonthlyJointCallId=System.currentPageReference().getParameters().get('retURL').substring(1,16);
        }catch(exception e){
           
        }
        Monthly_Joint_Call__c MonthlyJointCall=new Monthly_joint_call__c();
        try{
            MonthlyJointCall=[select MonthFormula__c,YearFormula__c,id from Monthly_Joint_Call__c where id=:MonthlyJointCallId limit 1];
        }catch(QueryException qe){
            MonthlyJointCall=null;
        }catch(exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,e.getMessage()));
        }
        if(MonthlyJointCall!=null)
            planMonth=date.newInstance(integer.valueof(MonthlyJointCall.YearFormula__c),integer.valueof(MonthlyJointCall.MonthFormula__c),1);
        if(MSRList==null)
            MSRList=new List<SelectOption>();
        else
            MSRList.clear();

        MSRList.add(new SelectOption('0','所有MSR'));
        
        showError=false;       
        allmsr=new list<user>(); 
        //搜索出所有MSR
        AllUserList=[select id,managerID,FunctionDepartment__c,Title__c,name,UserRegion__c,UserSubRegion__c,UserAreaValue__c,UserCity__c
                              from User where FunctionDepartment__c !='Trade Sales' order by Name];//搜出所有用户，排除TSR
       
       if(prof.Name=='System Administrator' || prof.Name=='系统管理员')
        {
            for(User u:AllUserList)//添加所有MSR
            {
                if(u.Title__c == 'Sales Rep' && u.FunctionDepartment__c =='Medical Sales'){
                    AllMsr.add(u);
                    MSRList.add(new SelectOption(u.Id,u.Name));
                }
            }
        }else{
            set<id> US=new set<id>();
            Us.add((id)userinfo.getuserid());
            SearchMsr(us);
        }
        JointCall.SearchDate__c = date.newInstance(integer.valueof(MonthlyJointCall.YearFormula__c), integer.valueof(MonthlyJointCall.MonthFormula__c), 1);
    }
    
    
    public PageReference Submit(){
        
        upsert UpsertJointCallList UniqueId__c;

        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }
    public PageReference Cancel(){

        pageReference pr = new pageReference('/'+ UrlId);     
        pr.setredirect(true);      
        return pr;
    }    
    
    
    public void search(){
        callplan.clear();
        showerror=false;
        msg = null;
        
        if(JointCall.SearchDate__c==null){
            NullCallDateError='请填写拜访日期。';
            showError=true;
        }
     
        if(JointCall.SearchDate__c!=null){
            if(JointCall.SearchDate__c.tostartofmonth()!=planmonth){
                NullCallDateError='您正在做的是'+planmonth.month()+'月份的计划，请选择正确的日期。';
                showError=true;
            }
        }
        if(JointCall.SearchDate__c!=null){
            if(JointCall.SearchDate__c > date.today())
            {
                NullCallDateError='不能选择今天之后的日期';
                showError=true;
            }      
            else
            {
                list<callplan__c> cpl=new list<callplan__c>();
                if(JointCall.SearchDate__c<>null && !showerror && JointCall.SearchDate__c <= date.today()){
        
                    if((MSRL != '0')&&(MSRL != null))
                    {
                       if((CityValue!= '0')&&(CityValue!= null))
                       {
                        cpl=[select id, ownerid__c,CreatedBy.Alias,name,CallPlanDate__c,Hospitalclass__c,HCPDepartment__c,HCP__c,CallPurpose__c,Monthly_Call_Plan__r.OwnerId,HCP__r.Id from callplan__c where Monthly_Call_Plan__r.OwnerId =: MSRL and 
                             salecity__c =:  CityValue and  CallPlanDate__c=:JointCall.SearchDate__c and CallWorkingtype__c='拜访' and PlanType__c =: '计划外'];              
                           
                       }
                       else
                       {
                        cpl=[select id, ownerid__c,CreatedBy.Alias,name,CallPlanDate__c,Hospitalclass__c,HCPDepartment__c,HCP__c,CallPurpose__c,Monthly_Call_Plan__r.OwnerId,HCP__r.Id from callplan__c where Monthly_Call_Plan__r.OwnerId =: MSRL and 
                              CallPlanDate__c=:JointCall.SearchDate__c and CallWorkingtype__c='拜访' and PlanType__c =: '计划外'];                         
                       
                       }

                    }
                    else
                    {
                         if((CityValue!= '0')&&(CityValue!= null))
                         {
                            cpl=[select id, ownerid__c,CreatedBy.Alias,name,CallPlanDate__c,Hospitalclass__c,HCPDepartment__c,HCP__c,CallPurpose__c,Monthly_Call_Plan__r.OwnerId,HCP__r.Id from callplan__c where  salecity__c =:  CityValue and CallPlanDate__c=:JointCall.SearchDate__c and CallWorkingtype__c='拜访'  and PlanType__c =: '计划外'];            
                                                 
                         }
                         else
                         {
                            cpl=[select id, ownerid__c,CreatedBy.Alias,name,CallPlanDate__c,Hospitalclass__c,HCPDepartment__c,HCP__c,CallPurpose__c,Monthly_Call_Plan__r.OwnerId,HCP__r.Id from callplan__c where  CallPlanDate__c=:JointCall.SearchDate__c and CallWorkingtype__c='拜访'  and PlanType__c =: '计划外'];            
                                                 
                         }   

                    }
        
                }
                list<JointCall__c> MyJointCallList = [Select id, CallPlan__c From JointCall__c Where CallDate__c=:JointCall.SearchDate__c and Owner__c =: userinfo.getuserid()];
                Boolean haveCall = false;
                for(callPlan__c cp:cpl){
                    haveCall = false;
                    for(JointCall__c j : MyJointCallList )
                    {
                        if(cp.id == j.CallPlan__c)
                            haveCall = true; 
                    }
                    if(!haveCall)
                        CallPlan.add(new callplanentry(cp));
                }
                if(cpl.size()<= 0)
                {
                    msg = '此代表未做'+ JointCall.SearchDate__c.year() + '年' + JointCall.SearchDate__c.month() + '月'+ JointCall.SearchDate__c.day() + '日'+'拜访计划';
                }
            }
        }
    }
    
    //====递归找出下级的所有MSR ====
    public void SearchMsr(set<id> US){
        set<id> tempS=new set<id>();
        temps.clear();
        
        for(user u:AllUserList){
            if(us.contains(u.managerID)){
                if(u.Title__c == 'Sales Rep' && u.FunctionDepartment__c=='Medical Sales'){
                    AllMsr.add(u);
                    MSRList.add(new SelectOption(u.Id,u.Name));
                }else{
                    temps.add(u.id);
                }
            }
        }
        if(temps.size()>0){
            SearchMsr(temps);
        }
    }
    
    //====筛选要显示的MSR
    public void MSRFilter(){
        MSRList.clear();
        MSRList.add(new SelectOption('0','所有MSR'));
        for(user u:AllMsr){
            if( u.UserCity__c.contains(CityValue) || cityvalue=='0' ){
                MSRList.add(new SelectOption(u.Id,u.Name));
            }
        }
    }
    //筛选城市
    public List<SelectOption> CityList
    {
        get
        {
            if(CityList==null)
                CityList=new List<SelectOption>();
            
            CityList.clear();
            CityList.add(new SelectOption('0','所有城市'));
            if(CurrentUser.UserCity__c==NULL)
            {
                if(CurrentUser.UserAreaValue__c!=null){
                
                    for(Place__c p:PlaceL)
                    {
                        if(p.PlaceType__c=='City' && String.valueOf(CurrentUser.UserAreaValue__c).contains(p.Area__r.Name)){
                            CityList.add(new SelectOption(P.Name,P.Name));
                        }
                    }   
                }else{
                    if(CurrentUser.UserSubRegion__c!=null){
                        for(Place__c p:PlaceL)
                        {
                            if(p.PlaceType__c=='City' && CurrentUser.UserSubRegion__c==p.Subregion__r.Name){
                                CityList.add(new SelectOption(P.Name,P.Name));
                            }
                        }   
                    }else{
                        if(CurrentUser.UserRegion__c!=null){
                            for(Place__c p:PlaceL)
                            {
                                if(p.PlaceType__c=='City' && CurrentUser.UserRegion__c==p.Region__r.Name){
                                    CityList.add(new SelectOption(P.Name,P.Name));
                                }
                            }
                        }
                    }
                }
                    
            }
            else
            {
                List<String> arr=String.valueOf(CurrentUser.UserCity__c).split(';');
                if(arr!=NULL || arr.size()>0)
                {
                    for(String s:arr)
                        CityList.add(new SelectOption(s,s));
                }
            }
            return CityList;
        }
       set;
    }

    
}